package com.hkbigdata.datagovernance.governance.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hkbigdata.datagovernance.ds.bean.TDsTaskDefinition;
import com.hkbigdata.datagovernance.ds.bean.TDsTaskInstance;
import com.hkbigdata.datagovernance.ds.service.TDsTaskDefinitionService;
import com.hkbigdata.datagovernance.ds.service.TDsTaskInstanceService;
import com.hkbigdata.datagovernance.governance.assess.Assessor;
import com.hkbigdata.datagovernance.governance.bean.AssessParam;
import com.hkbigdata.datagovernance.governance.bean.GovernanceAssessDetail;
import com.hkbigdata.datagovernance.governance.bean.GovernanceAssessGlobal;
import com.hkbigdata.datagovernance.governance.bean.GovernanceMetric;
import com.hkbigdata.datagovernance.governance.mapper.GovernanceAssessDetailMapper;
import com.hkbigdata.datagovernance.governance.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkbigdata.datagovernance.meta.bean.TableMetaInfo;
import com.hkbigdata.datagovernance.meta.service.TableMetaInfoExtraService;
import com.hkbigdata.datagovernance.meta.service.TableMetaInfoService;
import com.hkbigdata.datagovernance.utils.SpringBeanProvider;

import groovy.xml.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * <p>
 * 治理考评结果明细 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-01-08
 */
@DS("mysqlWriting")
@Service
public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService {
    @Autowired
    TableMetaInfoService tableMetaInfoService;
    @Autowired
    GovernanceMetricService governanceMetricService;
    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;
    @Autowired
    TDsTaskDefinitionService tDsTaskDefinitionService;
    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;
    @Autowired
    GovernanceAssessTableService governanceAssessTableService;
    @Autowired
    GovernanceAssessTecOwnerService governanceAssessTecOwnerService;
    @Autowired
    GovernanceAssessGlobalService governanceAssessGlobalService;



    @Override
    public void assessAllTableMetrics(String assessDate) {
        remove(new QueryWrapper<GovernanceAssessDetail>().eq("assess_date", assessDate));
        
        
//        1.获取表所有的元数据
        List<TableMetaInfo> tableMetaInfoList=tableMetaInfoService.getAllTableMeteInfo();
//        2.创建map集合存放所有表的元数据，k：库名加表名，v：tableMetaInfo，tips：方便后面的库名相似度评估类使用
        HashMap<String,TableMetaInfo>  fullTableMetaInfo=new HashMap<>();
        for (TableMetaInfo tableMetaInfo: tableMetaInfoList) {
            fullTableMetaInfo.put(tableMetaInfo.getSchemaName()+"."+tableMetaInfo.getTableName(),tableMetaInfo);
        }
//        2.获取所有的已启用的考评指标（governance_metric）
        List<GovernanceMetric> governanceMetricList = governanceMetricService.list(new QueryWrapper<GovernanceMetric>().ne("is_disabled","1"));

//        创建集合用于收集期货
        ArrayList<CompletableFuture<GovernanceAssessDetail>> completableFutures = new ArrayList<>();


//        3.新建考评细节对象的集合，用于保存所有的考评数据
        List<GovernanceAssessDetail> assessDetailList=new ArrayList<>(tableMetaInfoList.size()*governanceMetricList.size());


        //获取所有要考评的表名
        List<String> allTableName = tableMetaInfoList.stream().map(tableMetaInfo -> tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName()).collect(Collectors.toList());

        //获取表的任务定义
        Map<String, TDsTaskDefinition> dsTaskDefinitionMap = tDsTaskDefinitionService.getTDsTaskDefinitionByDt(assessDate, allTableName);

        //获取到DS中考评日期运行的实例
        List<TDsTaskInstance> tdsTaskInstanceByAssessDate = tDsTaskInstanceService.getTdsTaskInstanceByAssessDate(assessDate);





//        5.遍历获取所有的表并进行指标评估
        for(TableMetaInfo tableMetaInfo : tableMetaInfoList){
            for(GovernanceMetric governanceMetric: governanceMetricList){
                //创建考评参数对象
                Assessor assessor= SpringBeanProvider.getBean(governanceMetric.getMetricCode(),Assessor.class);
                //设置参数
                AssessParam assessParam=new AssessParam();
                assessParam.setAssessDate(assessDate);
                assessParam.setTableMetaInfo(tableMetaInfo);
                assessParam.setGovernanceMetric(governanceMetric);
                assessParam.setFullTableMetaInfo(fullTableMetaInfo);

                assessParam.setTDsTaskInstanceList(tdsTaskInstanceByAssessDate);
                assessParam.setTDsTaskDefinition(dsTaskDefinitionMap.get(tableMetaInfo.getSchemaName()+"."+tableMetaInfo.getTableName()));


                //进行指标考评
//                进行异步编排优化版本---------------------------------------------------------------
                CompletableFuture<GovernanceAssessDetail> assessDetailCompletableFuture = CompletableFuture.supplyAsync(new Supplier<GovernanceAssessDetail>() {
                    @Override
                    public GovernanceAssessDetail get() {
                        return assessor.metricAssess(assessParam);
                    }
                });
                completableFutures.add(assessDetailCompletableFuture);

//                原版-----------------------------------------------------------------------------
//              GovernanceAssessDetail governanceAssessDetail = assessor.metricAssess(assessParam);
                //将考评结果存储到集合中
//              assessDetailList.add(governanceAssessDetail);
            }
        }
//        6.将考评明细集合写到governance_assess_detail这个表中
            saveBatch(assessDetailList);
//                进行异步编排优化版本---------------------------------------------------------------
//        将收集到的期货集结
        List<GovernanceAssessDetail> governanceAssessDetailList = completableFutures.stream().map(governanceAssessDetailCompletableFuture ->
                governanceAssessDetailCompletableFuture.join()).collect(Collectors.toList());
        saveBatch(governanceAssessDetailList);

//                 原版---------------------------------------------------------------------------
//        5.将考评明细集合写到governance_assess_detail这个表中
//            saveBatch(assessDetailList)
    }
    

    @Override
    public void mainAssess(String assessDate) {
//        获取每个指标项考评
        assessAllTableMetrics(assessDate);

//        分数汇总
        governanceAssessTableService.calcGovernanceAssessTable(assessDate);
        governanceAssessTecOwnerService.calcAssessByTecOwner(assessDate);
        governanceAssessGlobalService.calcGlobalScore(assessDate);
    }

    @Override
    public Entity listMaps(QueryWrapper<GovernanceAssessDetail> governanceType, String s) {
        return null;
    }
}
